package com.zmc.product.application.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.zmc.common.constant.CacheConstants;
import com.zmc.common.domain.es.EsSkuEntity;
import com.zmc.common.domain.query.home.*;
import com.zmc.common.utils.JsonUtils;
import com.zmc.common.utils.PageUtils;
import com.zmc.common.utils.StringUtils;
import com.zmc.product.application.HomeApplicationService;
import com.zmc.product.infrastructure.entity.CommodityBannerEntity;
import com.zmc.product.infrastructure.entity.CommodityCategoryEntity;
import com.zmc.product.infrastructure.bean.response.BannerResp;
import com.zmc.product.infrastructure.bean.response.CategoryResp;
import com.zmc.product.infrastructure.service.CommodityBannerService;
import com.zmc.product.infrastructure.service.CommodityCategoryService;
import com.zmc.product.feign.SearchFeignService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：zmc
 * @Date：2024/10/31 9:38
 */

@Component
public class HomeApplicationServiceImpl implements HomeApplicationService {

    @Autowired
    private CommodityBannerService commodityBannerService;

    @Autowired
    private CommodityCategoryService commodityCategoryService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SearchFeignService searchFeignService;

    @Autowired
    private RedissonClient redissonClient;


    //todo
    public static String upLoadPrefix = "http://localhost:8080/api";


    @Override
    public List<BannerResp> getBanners(String distributionSite) {
        String bannerCache = stringRedisTemplate.opsForValue().get(CacheConstants.HOME_BANNER_KEY);
        if (StringUtils.isEmpty(bannerCache)) {
            RLock lock = redissonClient.getLock(CacheConstants.HOME_BANNER_KEY_LOCK);
            try {
                lock.lock();
               bannerCache = stringRedisTemplate.opsForValue().get(CacheConstants.HOME_BANNER_KEY);
                if (StringUtils.isEmpty(bannerCache)) {
                    List<CommodityBannerEntity> list = commodityBannerService.getListByType(distributionSite);
                    List<BannerResp> rest = new ArrayList<>();
                    for (CommodityBannerEntity entity : list) {
                        BannerResp resp = new BannerResp();
                        BeanUtils.copyProperties(entity, resp);
                        //todo
                        resp.setImgUrl(upLoadPrefix + entity.getImgUrl());
                        rest.add(resp);
                    }
                    stringRedisTemplate.opsForValue().set(CacheConstants.HOME_BANNER_KEY, JSON.toJSONString(rest));
                    return rest;
                }
            }finally {
                lock.unlock();
            }
        }
        return JSONArray.parseArray(bannerCache,BannerResp.class);
    }

    @Override
    public List<CategoryResp> getCategory() {
        String categoryCache = stringRedisTemplate.opsForValue().get(CacheConstants.HOME_CATEGORY_KEY);
        if (StringUtils.isEmpty(categoryCache)) {
            RLock lock = redissonClient.getLock(CacheConstants.HOME_CATEGORY_KEY_LOCK);
            try{
                lock.lock();
                categoryCache = stringRedisTemplate.opsForValue().get(CacheConstants.HOME_CATEGORY_KEY);
                if (StringUtils.isEmpty(categoryCache)) {
                    // 2、缓存中没有命中，查询数据库
                    List<CommodityCategoryEntity> categoryList = commodityCategoryService.list();
                    List<CategoryResp> res = new ArrayList<>();
                    categoryList.forEach(entity -> {
                        CategoryResp resp = new CategoryResp();
                        resp.setId(entity.getId());
                        resp.setName(entity.getName());
                        resp.setParentId(entity.getParentId());
                        res.add(resp);
                    });
                    //构建类目树形结构
                    List<CategoryResp> respList = CategoryResp.constructMenuTree(res, 0L);
                    // 3、查询的数据再放入缓存
                    stringRedisTemplate.opsForValue().set(CacheConstants.HOME_CATEGORY_KEY, JSON.toJSONString(respList));
                    return respList;
                }
            }finally {
                lock.unlock();
            }
        }
        return JSONArray.parseArray(categoryCache, CategoryResp.class);
    }

    @Override
    public PageUtils homeGoods(HomeKeywordFeignQuery query) {
        return  JsonUtils.transToArrayClassPage(searchFeignService.homeGoods(query), EsSkuEntity.class);
    }

    @Override
    public PageUtils totalGoods(HomeTotalFeignQuery query) {
        return JsonUtils.transToArrayClassPage(searchFeignService.totalGoods(query), EsSkuEntity.class);
    }

    @Override
    public PageUtils saleCountGoods(HomeSaleCountFeignQuery query) {
        return JsonUtils.transToArrayClassPage(searchFeignService.saleCountGoods(query), EsSkuEntity.class);
    }

    @Override
    public PageUtils hotGoods(HomeHotFeignQuery query) {
        return JsonUtils.transToArrayClassPage(searchFeignService.hotGoods(query), EsSkuEntity.class);
    }

    @Override
    public PageUtils priceGoods(HomeSalePriceFeignQuery query) {
        return JsonUtils.transToArrayClassPage(searchFeignService.priceGoods(query), EsSkuEntity.class);
    }

}
